<template>
	<div class="min-h-screen bg-gradient-to-br from-gray-50 via-blue-50 to-indigo-50">
		<!-- 背景装饰 -->
		<div class="fixed inset-0 overflow-hidden pointer-events-none">
			<div
				class="absolute -top-40 -right-40 w-80 h-80 bg-blue-200 rounded-full mix-blend-multiply filter blur-xl opacity-20 animate-blob">
			</div>
			<div
				class="absolute -bottom-40 -left-40 w-80 h-80 bg-purple-200 rounded-full mix-blend-multiply filter blur-xl opacity-20 animate-blob animation-delay-2000">
			</div>
			<div
				class="absolute top-40 left-40 w-80 h-80 bg-pink-200 rounded-full mix-blend-multiply filter blur-xl opacity-20 animate-blob animation-delay-4000">
			</div>
		</div>

		<!-- 主要内容区域 -->
		<div class="container mx-auto px-12 py-10 pt-32 relative z-10">
			<!-- 顶部：返回与标题 -->
			<div class="flex items-center justify-between mb-10">
				<div class="flex items-center gap-4">
					<el-button type="primary" link @click="goBack" class="text-gray-600 hover:text-gray-800 text-lg">
						<el-icon class="mr-2 text-xl">
							<ArrowLeft />
						</el-icon>
						返回班级详情
					</el-button>
					<h1 class="text-4xl font-bold text-gray-900">发布视频</h1>
				</div>
				<el-button type="primary" size="large" @click="showUploadDialog = true"
					class="rounded-full px-6 bg-gradient-to-r from-blue-500 to-indigo-600 hover:from-blue-600 hover:to-indigo-700 transition-all">
					<el-icon class="mr-2">
						<Upload />
					</el-icon>上传新视频
				</el-button>
			</div>

			<!-- 视频列表 -->
			<div class="bg-white rounded-3xl shadow-xl border border-gray-200 overflow-hidden">
				<div class="px-8 py-6 border-b border-gray-200 bg-gradient-to-r from-blue-50 to-indigo-50">
					<h3 class="text-2xl font-bold text-gray-900">已发布视频</h3>
				</div>

				<div v-if="videoList.length === 0" class="py-20 text-center">
					<div class="w-24 h-24 mx-auto mb-4 text-gray-300">
						<el-icon class="text-6xl">
							<VideoPlay />
						</el-icon>
					</div>
					<p class="text-gray-500 text-lg">暂无已发布的视频</p>
					<el-button type="primary" size="default" @click="showUploadDialog = true" class="mt-4">
						<el-icon class="mr-2">
							<Upload />
						</el-icon>发布第一个视频
					</el-button>
				</div>

				<div v-else class="p-8">
					<div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
						<div v-for="video in videoList" :key="video.id"
							class="bg-white rounded-2xl shadow-md border border-gray-200 overflow-hidden hover:shadow-lg transition-all">
							<div class="relative h-48 bg-gray-100">
								<div class="absolute inset-0 flex items-center justify-center">
									<el-icon class="text-6xl text-gray-400">
										<VideoPlay />
									</el-icon>
								</div>
								<div class="absolute top-3 right-3">
									<el-dropdown>
										<el-button type="text" size="small" class="text-gray-500 hover:text-gray-700">
											<el-icon>
												<More />
											</el-icon>
										</el-button>
										<template #dropdown>
											<el-dropdown-menu>
												<el-dropdown-item @click="handleDeleteVideo(video.id)">
													<el-icon class="text-red-500 mr-2">
														<Delete />
													</el-icon>删除
												</el-dropdown-item>
											</el-dropdown-menu>
										</template>
									</el-dropdown>
								</div>
								<div
									class="absolute bottom-3 right-3 bg-black bg-opacity-70 text-white text-xs px-2 py-1 rounded">
									{{ formatDuration(video.duration) }}
								</div>
							</div>
							<div class="p-5">
								<h4 class="text-lg font-bold text-gray-900 mb-2 line-clamp-1">{{ video.title }}</h4>
								<p class="text-gray-600 text-sm mb-4 line-clamp-2">{{ video.description }}</p>
								<div class="flex items-center justify-between text-sm text-gray-500">
									<span>{{ formatDate(video.uploadTime) }}</span>
									<span>{{ video.views }} 次观看</span>
								</div>
							</div>
						</div>
					</div>
				</div>
			</div>
		</div>

		<!-- 上传视频对话框 -->
		<el-dialog v-model="showUploadDialog" title="上传新视频" width="600px" :before-close="handleDialogClose">
			<div class="space-y-6 py-4">
				<el-form ref="uploadForm" :model="uploadForm" :rules="uploadRules">
					<el-form-item label="视频标题" prop="title">
						<el-input v-model="uploadForm.title" placeholder="请输入视频标题" />
					</el-form-item>

					<el-form-item label="视频描述" prop="description">
						<el-input v-model="uploadForm.description" placeholder="请输入视频描述" type="textarea" rows="4" />
					</el-form-item>

					<el-form-item label="上传视频" prop="videoFile">
						<el-upload class="upload-demo" action="/api/upload/video" :on-success="handleUploadSuccess"
							:on-error="handleUploadError" :on-progress="handleUploadProgress"
							:before-upload="beforeUpload" :file-list="fileList" accept="video/*" drag multiple="false">
							<el-icon class="el-icon--upload">
								<UploadFilled />
							</el-icon>
							<div class="el-upload__text">
								拖放视频文件到此处，或<em>点击上传</em>
							</div>
							<template #tip>
								<div class="el-upload__tip text-sm text-gray-500">
									支持 MP4、MOV、AVI 格式，最大支持 100MB
								</div>
							</template>
						</el-upload>

						<el-progress v-if="uploadProgress > 0 && uploadProgress < 100" :percentage="uploadProgress"
							class="mt-4" />
					</el-form-item>
				</el-form>
			</div>

			<template #footer>
				<el-button @click="showUploadDialog = false">取消</el-button>
				<el-button type="primary" @click="submitUpload" :loading="uploading">
					确认发布
				</el-button>
			</template>
		</el-dialog>
	</div>
</template>

<script setup>
	import {
		ref,
		reactive,
		onMounted
	} from 'vue'
	import {
		useRouter,
		useRoute
	} from 'vue-router'
	import {
		ElMessage,
		ElMessageBox,
		ElProgress
	} from 'element-plus'
	import {
		ArrowLeft,
		VideoPlay,
		Upload,
		More,
		Delete,
		UploadFilled
	} from '@element-plus/icons-vue'

	const router = useRouter()
	const route = useRoute()
	const classId = ref(route.params.classId)

	// 状态管理
	const showUploadDialog = ref(false)
	const fileList = ref([])
	const uploadProgress = ref(0)
	const uploading = ref(false)
	const videoList = ref([
		// 示例数据
		{
			id: 1,
			title: 'JavaScript 基础入门',
			description: '讲解JavaScript的基本语法和概念，适合初学者',
			duration: 1250, // 秒数
			uploadTime: new Date().toISOString(),
			views: 128
		},
		{
			id: 2,
			title: 'Vue3 组件化开发',
			description: '深入理解Vue3的组件化思想和实践方法',
			duration: 1820,
			uploadTime: new Date(Date.now() - 86400000).toISOString(),
			views: 89
		}
	])

	// 上传表单数据
	const uploadForm = reactive({
		title: '',
		description: '',
		videoFile: null
	})

	// 表单验证规则
	const uploadRules = {
		title: [{
				required: true,
				message: '请输入视频标题',
				trigger: 'blur'
			},
			{
				max: 100,
				message: '标题不能超过100个字符',
				trigger: 'blur'
			}
		],
		description: [{
			max: 500,
			message: '描述不能超过500个字符',
			trigger: 'blur'
		}],
		videoFile: [{
			required: true,
			message: '请上传视频文件',
			trigger: 'change'
		}]
	}

	// 生命周期
	onMounted(() => {
		// 实际项目中这里应该调用API获取视频列表
		console.log(`获取班级 ${classId.value} 的视频列表`)
	})

	// 方法
	const goBack = () => {
		router.push(`/class/${classId.value}`)
	}

	const handleUploadSuccess = (response, file, fileList) => {
		uploadProgress.value = 100
		ElMessage.success('视频上传成功')
		// 这里应该根据实际接口返回处理
		uploadForm.videoFile = response.data.fileId
	}

	const handleUploadError = (err) => {
		uploadProgress.value = 0
		ElMessage.error('视频上传失败，请重试')
		console.error(err)
	}

	const handleUploadProgress = (event) => {
		uploadProgress.value = Math.floor(event.percent)
	}

	const beforeUpload = (file) => {
		// 验证文件大小
		const isLt100M = file.size / 1024 / 1024 < 100
		if (!isLt100M) {
			ElMessage.error('视频文件大小不能超过100MB')
			return false
		}

		// 验证文件类型
		const isVideo = file.type.startsWith('video/')
		if (!isVideo) {
			ElMessage.error('请上传视频文件')
			return false
		}

		uploadProgress.value = 0
		return true
	}

	const submitUpload = () => {
		// 实际项目中这里应该调用API提交表单
		uploading.value = true

		// 模拟API请求
		setTimeout(() => {
			const newVideo = {
				id: Date.now(),
				title: uploadForm.title,
				description: uploadForm.description,
				duration: Math.floor(Math.random() * 1000 + 600),
				uploadTime: new Date().toISOString(),
				views: 0
			}

			videoList.value.unshift(newVideo)
			ElMessage.success('视频发布成功')
			showUploadDialog.value = false
			resetUploadForm()
			uploading.value = false
		}, 1000)
	}

	const handleDeleteVideo = (id) => {
		ElMessageBox.confirm(
			'确定要删除这个视频吗？此操作不可撤销。',
			'删除确认', {
				confirmButtonText: '确认',
				cancelButtonText: '取消',
				type: 'warning'
			}
		).then(() => {
			// 实际项目中这里应该调用API删除视频
			videoList.value = videoList.value.filter(video => video.id !== id)
			ElMessage.success('视频已删除')
		}).catch(() => {
			// 取消删除
		})
	}

	const handleDialogClose = () => {
		resetUploadForm()
		showUploadDialog.value = false
	}

	const resetUploadForm = () => {
		uploadForm.title = ''
		uploadForm.description = ''
		uploadForm.videoFile = null
		fileList.value = []
		uploadProgress.value = 0
	}

	// 工具函数
	const formatDuration = (seconds) => {
		const mins = Math.floor(seconds / 60)
		const secs = Math.floor(seconds % 60)
		return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`
	}

	const formatDate = (dateString) => {
		const date = new Date(dateString)
		return date.toLocaleString()
	}
</script>

<style scoped>
	/* 动画效果 */
	.animate-blob {
		animation: blob-morph 8s linear infinite;
	}

	.animation-delay-2000 {
		animation-delay: 2s;
	}

	.animation-delay-4000 {
		animation-delay: 4s;
	}

	@keyframes blob-morph {

		0%,
		100% {
			transform: scale(1) translate(0, 0);
		}

		25% {
			transform: scale(1.1) translate(20px, -20px);
		}

		50% {
			transform: scale(0.9) translate(0, 20px);
		}

		75% {
			transform: scale(1.05) translate(-20px, 10px);
		}
	}
</style>